// 获取上下文mContext
// 获取日历管理器calendarMgr
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import hilog from '@ohos.hilog';
import UIAbility from '@ohos.app.ability.UIAbility';
import Want from '@ohos.app.ability.Want';
import window from '@ohos.window';
import display from '@ohos.display'
import calendarManager from '@ohos.calendarManager';
import common from '@ohos.app.ability.common';
import abilityAccessCtrl, { PermissionRequestResult, Permissions } from '@ohos.abilityAccessCtrl';
import { BusinessError } from '@ohos.base';
import { permissions } from '../common/CheckPermission'

export let calendarMgr: calendarManager.CalendarManager | null = null;

export let mContext: common.UIAbilityContext | null = null;

import dataPreferences from '@ohos.data.preferences';

export let SettingPreferences: dataPreferences.Preferences | null = null;

// key不重复写入
export function SettingSet(key: string, value: boolean) {
  if (SettingPreferences != undefined) {
    if (SettingPreferences.hasSync(key)) {
      console.info("The key " + key + " is contained.");
      return
    } else {
      console.info("The key " + key + " does not contain.");
      // 此处以此键值对不存在时写入数据为例
      SettingPreferences.putSync(key, value);
      SettingPreferences.flush((err: BusinessError) => {
        if (err) {
          console.error(`The key Failed to flush. Code:${err.code}, message:${err.message}`);
          return;
        }
        console.info(`The key${key} Succeeded in flushing.`);
      })
    }
  }
}

//只在有key时修改
export function SettingChange(key: string, value: boolean) {
  if (SettingPreferences != undefined) {
    if (SettingPreferences.hasSync(key)) {
      console.info("The key " + key + " is contained.");
      // 此处以此键值对不存在时写入数据为例
      SettingPreferences.putSync(key, value);
      SettingPreferences.flush((err: BusinessError) => {
        if (err) {
          console.error(`The key Failed to flush. Code:${err.code}, message:${err.message}`);
          return;
        }
        console.info('The key Succeeded in flushing.');
      })
    } else {
      console.info("The key " + key + " is NOT contained.");
    }

  }
}

export function SettingGet(key: string) {
  if (SettingPreferences != undefined) {
    let val = SettingPreferences.getSync(key, "false");
    console.info("SettingGet：The " + key + " value is " + val);
    return val
  }
  return false
}

export default class EntryAbility extends UIAbility {
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
    // 绑定上下文信息
    AppStorage.setOrCreate('context', this.context);
    let context = this.context
  }

  onDestroy(): void {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
  }

  onWindowStageCreate(windowStage: window.WindowStage): void {
    // Main window is created, set main page for this ability
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
    // 获取首选项实例
    let options: dataPreferences.Options = {
      name: 'myStore'
    };
    SettingPreferences = dataPreferences.getPreferencesSync(this.context, options);

    /**
     * 设 置
     */
    SettingSet('iconSet', true)
    SettingSet('toneSet', false)
    SettingSet('vibratorSet', false) // 设置值，如果有了就不需要设定默认值了
    AppStorage.setOrCreate('iconSet', SettingPreferences.getSync('iconSet', true));
    AppStorage.setOrCreate('toneSet', SettingPreferences.getSync('toneSet', false));
    AppStorage.setOrCreate('vibratorSet', SettingPreferences.getSync('vibratorSet', false));

    AppStorage.setOrCreate('mContext', this.context);

    /**
     * 预置提示内容
     */
    SettingSet('preSet', true) // 首次会填写为true 持久化之后为false
    AppStorage.setOrCreate('preSet', SettingPreferences.getSync('preSet', false));

    // AppStorage.setOrCreate('Inspirations',SettingPreferences)
    windowStage.getMainWindow().then((windowObj) => {
      // this.windowObj = windowObj
      // // 获取应用启动时的窗口尺寸
      // this.updateBreakpoint(windowObj.getWindowProperties().windowRect.width)
      // // 注册回调函数，监听窗口尺寸变化
      // windowObj.on('windowSizeChange', (windowSize)=>{
      //   this.updateBreakpoint(windowSize.width)
      // })
    });


    windowStage.loadContent('pages/Index', (err, data) => {
      if (err.code) {
        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
        return;
      }
      windowStage.getMainWindowSync().setWindowBackgroundColor('#F2F4F5');
      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
    });
    mContext = this.context;
    // reqPermissionsFromUser(permissions,mContext)
    console.log('准备获取授权')
    let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
    // requestPermissionsFromUser会判断权限的授权状态来决定是否唤起弹窗
    atManager.requestPermissionsFromUser(mContext, permissions).then((data) => {
      let grantStatus: Array<number> = data.authResults;
      let length: number = grantStatus.length;
      for (let i = 0; i < length; i++) {
        if (grantStatus[i] === 0) {
          // 用户授权，可以继续访问目标操作
          console.log('获得授权')
          calendarMgr = calendarManager.getCalendarManager(mContext);
        } else {
          // 用户拒绝授权，提示用户必须授权才能访问当前页面的功能，并引导用户到系统设置中打开相应的权限
          console.log('用户拒绝授权，退出应用')
          return;
        }
      }
      // 授权成功
      console.log('授权成功')
    }).catch((err: BusinessError) => {
      console.error(`Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`);
    })


  }

  onWindowStageDestroy(): void {
    // Main window is destroyed, release UI related resources
    // hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
    // if (this.windowObj) {
    //   this.windowObj.off('windowSizeChange')
    // }
  }

  onForeground(): void {
    // Ability has brought to foreground
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
  }

  onBackground(): void {
    // Ability has back to background
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
  }
}